//
//  RegisterNextViewController.swift
//  d11
//
//  Created by Wai Yin Chan on 10/10/2017.
//  Copyright © 2017 Tech_001. All rights reserved.
//

import Foundation
import UIKit

class RegisterNextViewController: UITableViewController{
//    @IBOutlet weak var codeImageView: UIImageView!
//    @IBOutlet weak var textBirthday: NoActionTextField!
//    @IBOutlet weak var textQQ: UITextField!
//    @IBOutlet weak var textMobile: UITextField!
//    @IBOutlet weak var textEmail: UITextField!
//    @IBOutlet weak var textWithdrawPassword: UITextField!
//    @IBOutlet weak var textDCode: UITextField!
//    @IBOutlet weak var textCode: UITextField!
//    @IBOutlet weak var buttonPrevious: UIButton!
//    @IBOutlet weak var buttonReg: UIButton!
//    @IBOutlet weak var registerCellContentView: UIView!
//    @IBOutlet weak var buttonHidePassword: UIButton!
//    @IBOutlet weak var footerImageView: UIImageView!
//    //mt 20180130 解决代理包 传递推荐码
//    var agentCode:String?
//    var registerViewController: RegisterViewController?
//    var hiddenTablePath: [[Int]] = []
//    var hiddenInput: [UIControl] = []
//    var needHiddenParams: [String]?
//
//    var previousData: [String:String]?
//
//    var _loadView: UIView?
//
//    override func viewDidLoad() {
//        super.viewDidLoad()
//
//        let topLogo = UIImage(named: "icon_nav_left_logo")
//        let titleView = UIView()
//        let topLogoView = UIImageView(image: topLogo)
//        titleView.addSubview(topLogoView)
//        topLogoView.contentMode = .scaleToFill
//        topLogoView.frame = CGRect(x: -(137/2), y:-(35/2), width: 137, height: 35)
//        navigationItem.titleView = titleView
//        tableView.contentInset = UIEdgeInsets(top: -14, left: 0, bottom: 0, right: 0)
//        updateVerificationCode()
//        updateParam()
//        preparePickerView(textBirthday)
//
//        buttonHidePassword.setImage(UIImage(named: "show_password"), for: .selected)
//        let frameHeight = textWithdrawPassword.superview!.frame.height * 0.35 - 4
//        buttonHidePassword.imageEdgeInsets = UIEdgeInsets(top: frameHeight, left: frameHeight , bottom: frameHeight, right: frameHeight)
//
//        let gesture = UITapGestureRecognizer(target: self, action: #selector(self.updateVerificationCode))
//        codeImageView.isUserInteractionEnabled = true
//        codeImageView.addGestureRecognizer(gesture)
//
//        /**** Register Button mt****/
//        //        let button1 = UIBarButtonItem(title: "注册", style: .plain, target: self, action: #selector(self.register))
//        //        self.navigationItem.rightBarButtonItem = button1
//        let layerGradient = CAGradientLayer()
//        layerGradient.colors = [
//            UIColor.init(red: 1, green: 0.77, blue: 0.44, alpha: 1).cgColor,
//            UIColor.init(red: 0.99, green: 0.57, blue: 0.32, alpha: 1).cgColor
//        ]
//        layerGradient.frame = CGRect(x: 0, y: 0, width: view.bounds.width - 24, height: 56 - 8)
//
//        let layerGradient2 = CAGradientLayer()
//        layerGradient2.colors = [
//            UIColor.init(red: 1, green: 0.77, blue: 0.44, alpha: 1).cgColor,
//            UIColor.init(red: 0.99, green: 0.57, blue: 0.32, alpha: 1).cgColor
//        ]
//        layerGradient2.frame = CGRect(x: 0, y: 0, width: view.bounds.width - 24, height: 56 - 8)
//
//        buttonPrevious.layer.addSublayer(layerGradient)
//        buttonPrevious.layer.cornerRadius = 5
//        buttonReg.layer.addSublayer(layerGradient2)
//        buttonReg.layer.cornerRadius = 5
//
//        buttonPrevious.setTitle("上一步", for: .normal)
//        buttonPrevious.setTitleColor(UIColor.white, for: .normal)
//        buttonPrevious.clipsToBounds = true
//        buttonReg.setTitle("注册", for: .normal)
//        buttonReg.setTitleColor(UIColor.white, for: .normal)
//        buttonReg.clipsToBounds = true
//
//        buttonPrevious.addTarget(self.registerViewController, action: #selector(self.registerViewController?.backPrevious), for: .touchUpInside)
//        buttonReg.addTarget(self, action: #selector(register), for: .touchUpInside)
//
//        let stackView = TZStackView()
//        stackView.axis = .vertical
//        stackView.distribution = .fillEqually
//        stackView.spacing = 8
//
//        registerCellContentView.addSubview(stackView)
//
//        stackView.addArrangedSubview(buttonPrevious)
//        stackView.addArrangedSubview(buttonReg)
//
//        stackView.translatesAutoresizingMaskIntoConstraints = false
//        //        stackView.anchors.topAnchor.constraintEqualToAnchor(anchor: registerCellContentView.anchors.topAnchor, constant: 8).isActive = true
//        //        stackView.anchors.bottomAnchor.constraintEqualToAnchor(anchor: registerCellContentView.anchors.bottomAnchor, constant: 8).isActive = true
//        stackView.anchors.centerYAnchor.constraintEqualToAnchor(anchor: registerCellContentView.anchors.centerYAnchor).isActive = true
//        stackView.anchors.centerXAnchor.constraintEqualToAnchor(anchor: registerCellContentView.anchors.centerXAnchor).isActive = true
//        stackView.anchors.widthAnchor.constraintEqualToAnchor(anchor: registerCellContentView.anchors.widthAnchor, multiplier: 1, constant: -24).isActive = true
//        stackView.anchors.heightAnchor.constraintEqualToAnchor(anchor: registerCellContentView.anchors.heightAnchor, multiplier: 0.9, constant: 0).isActive = true
//        //        stackView.anchors.leadingAnchor.constraintEqualToAnchor(anchor: registerCellContentView.anchors.leadingAnchor, constant: 12).isActive = true
//        //        stackView.anchors.trailingAnchor.constraintEqualToAnchor(anchor: registerCellContentView.anchors.trailingAnchor, constant: 12).isActive = true
//
//        if kIsIpad == true {
//            footerImageView.image = UIImage.init(named: "wanb_footer_ipad")
//        }else{
//            footerImageView.image = UIImage.init(named: "wanb_footer")
//        }
//    }
//
//    override func viewWillDisappear(_ animated: Bool) {
//        super.viewWillAppear(animated)
//
//        let nextData: [String:String?] = [
//            "regbirthday": textBirthday.text,
//            "regqq": textQQ.text,
//            "reqphone": textMobile.text,
//            "regemail": textEmail.text,
//            "withdrawpassword": textWithdrawPassword.text,
//            "dcode": textDCode.text,
//            ]
//
//        self.registerViewController?.nextData = nextData
//    }
//
//    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
//        if self.hiddenTablePath.contains(where: { $0 == [indexPath[0], indexPath[1]]}) {
//            return 0.2
//        }
//
//        if indexPath.section == 1{
//            if indexPath.row == 1{
//                return 487
//            }
//            return 112
//        }
//
//        return 44.0
//    }
//
//    @IBAction func buttonHidePasswordClick(_ sender: UIButton) {
//        textWithdrawPassword.isSecureTextEntry = !textWithdrawPassword.isSecureTextEntry
//        sender.isSelected = !sender.isSelected
//    }
//
//    func endEditing(){
//        view.endEditing(true)
//    }
//
//    func preparePickerView(_ textField: UITextField) {
//        let view = UIView()
//
//        let headerView = UIView()
//        headerView.frame = CGRect(x: 0, y: 0, width: UIHelper.fullSize.width, height: 40.0)
//        headerView.backgroundColor = UIColor.groupTableViewBackground
//
//        let finishButton = UIButton()
//        finishButton.setTitle("完成", for: .normal)
//        finishButton.addTarget(self, action: #selector(self.handleDateChange(sender:)), for: .touchUpInside)
//        finishButton.setTitleColor(UIColor.init(red: 0.08, green: 0.49, blue: 0.98, alpha: 1), for: .normal)
//        finishButton.frame = CGRect(x: UIHelper.fullSize.width - 60, y: 0, width: 60.0, height: 40.0)
//
//        let datePickerView  : UIDatePicker = UIDatePicker()
//        datePickerView.datePickerMode = UIDatePicker.Mode.date
//        datePickerView.addTarget(self, action:#selector(self.handleDateChange(sender:)), for: UIControl.Event.valueChanged)
//        datePickerView.frame = CGRect(x: 0, y: 44, width: UIHelper.fullSize.width, height: datePickerView.frame.height)
//
//        headerView.addSubview(finishButton)
//        view.addSubview(datePickerView)
//        view.addSubview(headerView)
//
//        let viewHeight = headerView.frame.height + datePickerView.frame.height
//        view.frame = CGRect(x: 0, y: 0, width: UIHelper.fullSize.width, height: viewHeight)
//
//        UIHelper.addTopBorder(inView: headerView)
//
//        textField.inputView = view
//    }
//
//    @objc func handleDateChange(sender: UIControl) {
//        if sender is UIButton {
//            view.endEditing(true)
//            return
//        }
//
//        if let datePicker = sender as? UIDatePicker {
//            let dateFormatter = DateFormatter()
//            dateFormatter.dateFormat = "yyyy-MM-dd"
//
//            textBirthday.text = dateFormatter.string(from: datePicker.date)
//        }
//    }
//
//    @IBAction func emailEdit(_ sender: Any) {
//        var textWord:String = (sender as! UITextField).text!
//
//        RequestHelper.get("www.manx97.com",atPath: "/home/enableEmail?email=\(textWord)",withCompletion: { data in
//            let mtisdata:String=String.init(data:data,encoding:.utf8)!
//            if(mtisdata=="false"){
//                DispatchQueue.main.async{
//                    (sender as! UITextField).becomeFirstResponder(); UIHelper.alertSimpleMessage(about:"错误提示", withDescription: "邮箱已被注册",in:self)}
//            }
//        },withError:{error in
//
//        })
//    }
//    @objc func register(){
//        self.view.endEditing(true)
//
//        var requestParams: [String: String] = [
//            //   "wdpassword": "",
//            "birthyear": "0",
//            "birthmonth": "0",
//            "birthday": "0",
//            "gender": "0",
//            ]
//
//        var isMissingFields = false
//        let inputs: [UITextField:String] = [
//            textWithdrawPassword: "wdpassword",
//            textEmail: "email",
//            textMobile: "uphone",
//            textQQ: "qq",
//            textCode: "verifycode",
//            textBirthday: "regbirthday"
//        ]
//
//        func checkCondition(text: String, withPattern: String) -> Bool {
//            if let range = text.range(of: withPattern, options: .regularExpression){
//                let subString = text.substring(with: range)
//                return !text.isEmpty && subString == text
//            }
//            return false
//        }
//        let inputsCondition: [UIControl:[String]] = [
//            //textWithdrawPassword: ["[0-9]{6}", "取款密码须为6字符之纯数字"],
//            textWithdrawPassword: ["^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+){6,16}", "取款密码限定6-16位数字及字母组合"],
//            textEmail: [".*", ""],
//            textMobile: ["[0-9]{11,11}", "手机号码长度须为11位"],
//            textQQ: [".*", ""],
//            textCode: [".*", ""],
//            textBirthday: [".*", ""]
//        ]
//
//        for key in inputs.keys {
//            if hiddenInput.contains(key) == false {
//                if let text = key.text {
//                    if text.count > 0 {
//                        //Input entered
//                        if let condition = inputsCondition[key] {
//                            if checkCondition(text: text, withPattern: condition[0]) {
//                                requestParams[inputs[key]!] = text
//                            }else{
//                                key.becomeFirstResponder()
//                                UIHelper.alertSimpleMessage(about: "", withDescription: condition[1], in: self)
//                                return
//                            }
//                        }
//                    }else{
//
//                        //Empty String
//                        isMissingFields = true
//                    }
//                }else{
//
//                    //Nil
//                    isMissingFields = true
//                }
//            }
//        }
//
//        //Checking Ends
//        if isMissingFields{
//            UIHelper.alertSimpleMessage(about: "注册失败", withDescription: "请您按照注册所需信息填写所有栏位，感谢您的配合。", in: self)
//        }else{
//            if self.needHiddenParams!.contains("regbirthday") == false {
//                //Check Date
//                let strTime = textBirthday.text!
//                let formatter = DateFormatter()
//                formatter.dateFormat = "yyyy-MM-dd"
//
//                let calendar = NSCalendar.current
//                let firstDate = Date()
//                let secondDate = formatter.date(from: strTime)!
//                if(secondDate < firstDate){
//                    let date1 = calendar.startOfDay(for: firstDate)
//                    let date2 = calendar.startOfDay(for: secondDate)
//                    let components = calendar.dateComponents([.year], from: date1, to: date2)
//
//                    /*if (components.year! * -1) < 18 {
//                     UIHelper.alertSimpleMessage(about: "注册失败", withDescription: "你必须届满合法博彩年龄", in: self)
//                     return
//                     }else{*/
//                    //Birthday OK
//                    requestParams["birthyear"] = String(calendar.component(.year, from: secondDate))
//                    requestParams["birthmonth"] = String(calendar.component(.month, from: secondDate))
//                    requestParams["birthday"] = String(calendar.component(.day, from: secondDate))
//                    //}
//                }else{
//                    UIHelper.alertSimpleMessage(about: "注册失败", withDescription: "您输入的出生日期有误，请您重新输入", in: self)
//                    return
//                }
//            }
//
//            //Agc
//            if let agc = textDCode.text {
//
//                if self.agentCode != nil{
//                    requestParams["agc"] = self.agentCode
//                }else{
//                    if agc.count > 0 {
//
//                        requestParams["agc"] = agc
//                    }else{
//                        //代理包进入
//
//                        requestParams["agc"] = "10000"
//                    }
//                }
//            }else{
//
//                requestParams["agc"] = "10000"
//            }
//
//            //Prepare to Register
//            for key in self.previousData!.keys {
//                if key != "regbirthday"{
//                    requestParams[key] = self.previousData![key]
//                }
//            }
//
//            print(requestParams)
//            actionRegister(withParams: requestParams)
//        }
//    }
//
//    func updateParam(){
//        let associatedIndexPaths: [String: [Int]] = [
//            "withdrawpassword": [0,1],
//            "dcode": [0,0],
//            "regemail": [0,2],
//            "reqphone": [0,3],
//            "regqq": [0,4],
//            "regbirthday": [0,5],
//
//            ]
//
//        let associatedInput: [String: UIControl] = [
//            "regbirthday": self.textBirthday,
//            "regqq": self.textQQ,
//            "reqphone": self.textMobile,
//            "regemail": self.textEmail,
//            "withdrawpassword": self.textWithdrawPassword,
//            "dcode": self.textDCode,
//            ]
//
//        for key in needHiddenParams! {
//            if let val = associatedIndexPaths[key] {
//                self.hiddenTablePath.append(val)
//                self.hiddenInput.append(associatedInput[key]!)
//            }
//        }
//
//        /**** Saved Data ****/
//        if let data = self.registerViewController?.nextData {
//            for key in data.keys {
//                if let textField = associatedInput[key] as? UITextField{
//                    if let text = data[key] {
//                        textField.text = text
//                    }
//                }
//            }
//        }
//    }
//
//    @objc func updateVerificationCode(){
//        RequestHelper.get(atPath: "/service/verifycode", withCompletion: { data in
//            let imageData:NSData = NSData(data: data)
//
//            // When from background thread, UI needs to be updated on main_queue
//            DispatchQueue.main.async {
//                self.codeImageView.image = UIImage(data: imageData as Data)
//            }
//        }, withError: { error in
//            print(error)
//        })
//    }
//
//    func actionRegister(withParams params: [String:String]){
//        self._loadView?.removeFromSuperview()
//        self._loadView = UIHelper.initLoadView(self, offsetY: -64)
//        self.view.addSubview(self._loadView!)
//
//
//        RequestHelper.post(atPath: "/kz/member/account", withData: params, withCompletion: { data in
//            let dataArray = try JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
//            let code = dataArray["c"] as! Int
//            print(dataArray)
//
//            DispatchQueue.main.async {
//                self._loadView?.removeFromSuperview()
//                switch code{
//                case 0:
//                    let dialogMessage = UIAlertController(title: "注册成功，请登录", message: "", preferredStyle: .alert)
//                    dialogMessage.view.tintColor = UIColor.black
//                 //   ToolHelper.statisticsPage(pageName: "注册：注册成功")
//                    // Create OK button with action handler
//                    let ok = UIAlertAction(title: "知道了", style: .default, handler: { (action) -> Void in
//                        UserDefaults.standard.set(params["joiname"], forKey: DefaultKey.USER_LOGIN_NAME)
//                        //                        UserDefaults.standard.set(true, forKey: DefaultKey.USER_IS_SAVE_PASSWORD)
//                        DispatchQueue.main.async(execute: {
//
//                            if let controller = self.navigationController?.viewControllers[0] as? LoginViewController {
//                                controller.textPassword.text = params["joiname"]
//                                controller.textPassword.text = params["joinpwd"]
//                                controller.shouldNotEmptyPasswordField = true
//                            }
//
//                            self.navigationController?.popToRootViewController(animated: true)
//                        })
//                    })
//
//                    //Add OK and Cancel button to dialog message
//                    dialogMessage.addAction(ok)
//
//                    // Present dialog message to user
//                    self.present(dialogMessage, animated: true, completion: nil)
//                case 998:
//                    UIHelper.alertSimpleMessage(about: "注册失败", withDescription: "您输入的验证码有误，请重新输入", in: self)
//                    self.updateVerificationCode()
//                case 1101:
//
//                    let msg = dataArray["m"] as! String
//
//                    if msg.contains("joiname") {
//                        UIHelper.alertSimpleMessage(about: "注册失败", withDescription: "您输入的账号有误（4-11个字符, 仅可输入英文字母以及数字的组合），请重新输入。", in: self)
//
//                    }
//                    if msg.contains("joinpwd") {
//                        UIHelper.alertSimpleMessage(about: "注册失败", withDescription: "您输入的密码有误（密码长度为6-16个字符,须含有字母和数字组合），请重新输入", in: self)
//
//                    }
//                    if msg.contains("wdpassword") {
//                        UIHelper.alertSimpleMessage(about: "注册失败", withDescription: "您输入的取款密码有误密码长度为6-16个字符,须含有字母和数字组合），请重新输入", in: self)
//
//                    }
//                    if msg.contains("fullname") {
//                        UIHelper.alertSimpleMessage(about: "注册失败", withDescription: "您输入的真实姓名有误，请您核对您的账号信息，账号关系到您的资金安全，请您核对后重新输入", in: self)
//
//                    }
//                    if msg.contains("mobile") || msg.contains("uphone") {
//                        UIHelper.alertSimpleMessage(about: "注册失败", withDescription: "您输入的手机号码有误（11位真实手机号码），请您重新输入", in: self)
//
//                    }
//                    if msg.contains("email") {
//                        UIHelper.alertSimpleMessage(about: "注册失败", withDescription: "邮箱有误，请重新输入", in: self)
//
//                    }
//                    //                    if msg.contains("qq") {
//                    //                        UIHelper.alertSimpleMessage(about: "注册失败", withDescription: "您输入的QQ号码有误，请重新输入", in: self)
//                    //
//                    //                    }
//                    //                    if msg.contains("gender") {
//                    //                        UIHelper.alertSimpleMessage(about: "注册失败", withDescription: "您尚未选择您的性别，万博为不同用户准备了个性化定制的礼品，为了保障您可以收到适合的礼品，请您如实填写您的性别信息", in: self)
//                    //                    }
//                    self.updateVerificationCode()
//                case 1103:
//                    UIHelper.alertSimpleMessage(about: "注册失败", withDescription: "您输入的账号已被使用（4-11个字符, 仅可输入英文字母以及数字的组合），请您重新输入", in: self)
//                    self.updateVerificationCode()
//                default:
//                    UIHelper.alertSimpleMessage(about: "注册失败", withDescription: "发生错误", in: self)
//                    self.updateVerificationCode()
//                }
//            }
//        }, withError: { error in
//            print(error)
//            DispatchQueue.main.async {
//                UIHelper.alertSimpleMessage(about: "注册失败", withDescription: "发生错误", in: self)
//                self.updateVerificationCode()
//            }
//        })
//    }
    
}
